package com.wangsong.controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpStatus;

import com.wangsong.model.JWTToken;
import com.wangsong.service.ShiroService;
import com.wangsong.util.JWTUtil;

@RestController
@ControllerAdvice
public class ShiroWebController {


    @GetMapping("/shiro/login")
    public String login(@RequestParam("username") String username,
                              @RequestParam("password") String password) {
    	String s=JWTUtil.sign(username, password);
    	Subject subject = SecurityUtils.getSubject();
    	try{
    		subject.login(new JWTToken(s));
    	}catch (Exception e) {
    		return null;
		}
        return s;
        
    }

    @GetMapping("/shiro/article")
    public String article() {
        return "要登录无权限";
    }

    @GetMapping("/shiro/require_auth")
    @RequiresPermissions(logical = Logical.AND, value = {"view", "edit"})
    public String requireAuth() {
        return "要登录有权限";
    }

    @ExceptionHandler(value = UnauthorizedException.class) 
	public String unauth()  { 
	     return "无权限"; 
	} 

    // 捕捉其他所有异常
    @ExceptionHandler(UnauthenticatedException.class)
    public String globalException(HttpServletRequest request, HttpServletResponse response,Throwable ex) {
        return "token错误";
    }
 
}
